package main.strategy;

import enumeration.EnumRobStrategy;
import main.robClass;
import mysql.MysqlUtil;
import org.apache.http.MethodNotSupportedException;
import robber.AbstractRobber;
import robber.IRobber;
import user.IUser;
import robber.impl.PERobber;
import user.impl.robUser.IRobUser;
import user.impl.robUser.RobUser;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Scanner;

/**
 * 选择体育课列表
 */
public class SelectPECourseListStrategy extends SelectCourseListStartegy {


    @Override
    synchronized
    protected void robListCourse(IUser user) {

        RobUser robUser = ((RobUser) user);
        IRobber iRobber = robUser.getIRobber();
        if (iRobber == null) {
            iRobber = new PERobber(user);
            robUser.setIRobber(iRobber);
        }

        HashMap<String, String> classSelects = null;
        try {
            classSelects = iRobber.syncSearchClasses();
            if (classSelects == null) {
                robClass.logger.info("找不到课程列表");
                return;
            }
        } catch (Exception e) {
            robClass.logger.info("找不到课程列表");
            //e.printStackTrace();
        }
        try {
            classSelects.entrySet().stream().forEach(x -> robClass.logger.info("课名：" + x.getKey() + "  id:" + x.getValue()));
        } catch (Exception e) {
            e.printStackTrace();
        }


        Scanner keyBoardInput = new Scanner(System.in, "UTF-8");
        while (keyBoardInput.hasNext()) {
            String classIdInput = keyBoardInput.next();
            if (classIdInput.equalsIgnoreCase("exit")) {
                ((RobUser) user).setEnumRobStrategy(EnumRobStrategy.LIST);
                MysqlUtil.updateUser(robUser);
                robUser.showRobCourses();
                break;
            }
            //todo 注意这里的NULL情况

            Optional<Map.Entry<String, String>> IdAndCourseName = ((AbstractRobber) iRobber).getIdAndCourseNameCache().entrySet().stream().filter(
                    course -> course.getKey().equalsIgnoreCase(classIdInput)
            ).findFirst();
            if (IdAndCourseName.isPresent()) {
                ((RobUser) user).getRobClasses().add(classIdInput);
            } else {
                robClass.logger.info("你输入的课程id有误! 请重新输入!");
            }
        }

        robClass.showTable(user);

    }

    //todo not 感觉随机抢课不实用 先不写了
    @Override
    protected void robRandomCourse(IUser user, HashMap<String, String> classSelects) {
        try {
            throw new MethodNotSupportedException("不支持的操作");
        } catch (MethodNotSupportedException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void robAllCourse(IUser user, HashMap<String, String> classSelects) {
        classSelects.entrySet().stream().forEach(x -> ((IRobUser) user).getRobClasses().add(x.getValue()));
        ((IRobUser) user).setEnumRobStrategy(EnumRobStrategy.ALL);
    }

}
